<template>
  <div class="tags-box">
    <el-tag closable @close="del(tag)" :type="type" v-for="tag in value" :key="tag">{{ tag }} </el-tag>
    <el-tag v-show="!isEdit" :type="type" class="add" @click="edit" :disable-transitions="true"> + </el-tag>
    <el-input
      v-show="isEdit"
      v-model.trim="input"
      v-focus
      clearable
      size="mini"
      class="input"
      @keyup.native.enter="enter"
      @keyup.native.esc="esc"
      @blur="blur"
      ref="input"
    />
  </div>
</template>

<script>
/**
 * 事件
 * add
 * 添加标签时触发
 * 参数
 * 添加的文本
 */
export default {
  name: 'tags',
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    type: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      isEdit: false,
      input: '',
    }
  },
  methods: {
    edit() {
      this.isEdit = true
      this.$nextTick(() => {
        this.$refs.input.focus()
      })
    },
    enter() {
      this.$refs.input.blur()
      this.isEdit = true
    },
    esc() {
      this.input = ''
      this.$refs.input.blur()
    },
    blur() {
      if (this.value.includes(this.input)) return this.$message.warning('出现重复内容')
      this.isEdit = false
      if (!this.input) return
      this.value.push(this.input)
      this.$emit('input', this.value)
      this.$emit('change', this.value)
      this.$emit('blur', this.value)
      this.input = ''
    },
    /**删除 */
    del(v) {
      this.value.splice(this.value.indexOf(v), 1)
      this.$emit('input', this.value)
      this.$emit('change', this.value)
      this.$emit('blur', this.value)
    },
  },
}
</script>

<style lang="scss" scoped>
.add {
  cursor: pointer;
}
.el-tag {
  margin: 3px 0;
  margin-right: 6px;
}
.input {
  width: 90px;
  height: 28px;
}
</style>
